package Test09;

//反射

/*
Class类中用于获取构造方法的方法
    Constructor<?>[]getConstructors():返回==所有公共==构造方法对象的数组
    Constructor<?>[]getDeclaredConstructors():返回==所有==构造方法对象的数组
    Constructor\<T>getConstructor(class<?>...parameterTypes):返回==单个公共==构造方法对象
    Constructor\<T>getDeclaredConstructor(Class<?>.. parameterTypes):返回==单个==构造方法对象

Constructor类中用于创建对象的方法
    T newInstance(Object...initargs):根据指定的构造方法创建对象
    setAccessible(boolean flag):设置为true,表示取消访问检查
 */

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test02 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {

        //1、获取class字节码文件对象
        Class clazz = Class.forName("Test09.Student02");

        //2、获取构造方法

        /*Constructor[] cons1 = clazz.getConstructors();
        for (Constructor con : cons1) {
            System.out.println(con);
        }*/

        /*Constructor[] cons2 = clazz.getDeclaredConstructors();
        for (Constructor con : cons2) {
            System.out.println(con);
        }*/

        /*Constructor con1 = clazz.getConstructor();
        System.out.println(con1);

        Constructor con2 = clazz.getDeclaredConstructor(String.class);
        System.out.println(con2);

        Constructor con3 = clazz.getDeclaredConstructor(int.class);
        System.out.println(con3);*/

        Constructor con4 = clazz.getDeclaredConstructor(String.class, int.class);


        /*int modifiers = con4.getModifiers();//获取权限修饰符
        System.out.println(modifiers);

        System.out.println("=======================================");

        Parameter[] parameters = con4.getParameters();
        for (Parameter parameter : parameters) {
            System.out.println(parameter);
        }*/

        //暴力反射：表示临时取消权限校验
        con4.setAccessible(true);
        Student02 stu = (Student02) con4.newInstance("张三", 23);

        System.out.println(stu);

    }
}

class Student02 {

    private String name;
    private int age;

    public Student02() {
    }

    public Student02(String name) {
        this.name = name;
    }

    protected Student02(int age) {
        this.age = age;
    }

    private Student02(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     *
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     *
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     *
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "Student02{name = " + name + ", age = " + age + "}";
    }
}
